package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.dto.LoginDto;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-06-27
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {

    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser wmUser) {
        //判断用户是否存在
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getApUserId,wmUser.getApUserId());
        WmUser one = this.getOne(queryWrapper);
        if(one==null){
            wmUser.setCreatedTime(new Date());
            this.baseMapper.insert(wmUser);
        }
        return ResponseResult.okResult(wmUser);
    }

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //如果用户不存在,以及用户名和数据库不一样,以及密码不对都直接返回错误提示
        if(loginDto==null|| StringUtils.isEmpty(loginDto.getName())||StringUtils.isEmpty(loginDto.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户查询
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName,loginDto.getName());
        WmUser wmUser = this.getOne(queryWrapper);
        //判断是否存在
        if(wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //如果存在,获取盐,使用用户传入的密码＋盐.进行md5计算
        String salt = wmUser.getSalt();
        String s = loginDto.getPassword() + salt;
        String md5Hex = DigestUtils.md5Hex(s);
        //对比md5值和仓库中存放的密码
        if(!md5Hex.equals(wmUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码一致,则使用JWt生成token.使用用户id生成
        Map<String,Object> objectMap = new HashMap<>();
        objectMap.put("userId",wmUser.getId());
        objectMap.put("userName",wmUser.getName());
        String token = AppJwtUtil.getToken(objectMap);
        //定义返回的结果
        Map<String,Object> map = new HashMap<>();
        //脱敏处理
        wmUser.setPassword("");
        wmUser.setSalt("");
        wmUser.setPhone("");
        map.put("user",wmUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
